package web.sms.mvc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import web.sms.core.pojo.JsonInfo;
import web.sms.mvc.entity.User;
import web.sms.mvc.service.UserService;
import web.sms.mvc.service.WechatService;
import web.sms.utils.StringUtils;
import web.sms.utils.URLConnectionHelper;

import javax.servlet.http.HttpServletRequest;

/**
 * 时间： 2018/1/25
 *
 * @author Eoly
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {

    private final String WECHAT_TOKEN = "qazwsxedc1234";
    private final String APP_ID = "wx5f7c67aed1e686ea";
    private final String SECRET = "6194fcf6437d2fd1f833938f8977ffdc";


    private final WechatService wechatService;
    private final UserService userService;

    @Autowired
    public WechatController(WechatService wechatService, UserService userService) {
        this.wechatService = wechatService;
        this.userService = userService;
    }

    /**
     * 微信服务器信息接收验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @ResponseBody
    @RequestMapping("/receive")
    public String receive(
            String signature,
            String timestamp,
            String nonce,
            String echostr
    ) {
        String resultStr = "wrong request!";
        if (StringUtils.checkSignature(WECHAT_TOKEN, signature, timestamp, nonce)) {
            resultStr = echostr;
        }
        return resultStr;
    }

    /**
     * 用于将链接转入微信开放平台认证以拉取用户信息
     *
     * @param url     回调重定向链接
     * @param request
     * @return
     */
    @RequestMapping("/redirect")
    public String redirect(String url, HttpServletRequest request) {
        StringBuffer url1 = request.getRequestURL();
        String tempContextUrl = url1.delete(url1.length() - request.getRequestURI().length(), url1.length()).toString();
        String context = request.getContextPath();
        if (url == null || "".equals(url)) {
            url = "/wechat/bind.html";
        }
        url = context + url;
        url = tempContextUrl + url;
        return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID + "&redirect_uri=" + url + "?response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect";
    }

    @RequestMapping(value = "/bind.html", method = RequestMethod.GET)
    public String bindPage(
            @RequestParam
                    String code,
            Model model
    ) {

        String URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"
                .replace("APPID", APP_ID).replace("SECRET", SECRET).replace("CODE", code);
        // URLConnectionHelper是一个模拟发送http请求的类
        String jsonStr = URLConnectionHelper.sendGet(URL, param);
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        String openid = jsonObj.get("openid").toString();

        //String openid = "lodsajjsadjosadijasd";
        // 在session中保存openid;
        SecurityUtils.getSubject().getSession().setAttribute("openid", openid);
        // 获取与该id绑定的用户
        User checkUser = new User();
        checkUser.setUserOpenId(openid);
        User resultUser = userService.findUserByOpenId(openid);
        if (resultUser == null) {
            return "redirect:/wechat/redirect-do?url=/resources/h5/app/index.html&sharp=bind";
        }
        // 绑定用户模拟登录
        User authUserInfo = userService.findUserWithAuthenticationInfo(resultUser.getUserId());
        userService.doLogin(authUserInfo.getUserLoginName(), authUserInfo.getUserPassword() + "|cangshi");
        return "redirect:/wechat/redirect-do?url=/resources/h5/app/index.html";





        /*[不用获取用户信息，只需要openid故无需此步骤]// 获取 access_token
        String token = wechatService.getAccessToken(false);
        // 有了用户的openid就可以的到用户的信息了
        String info = URLConnectionHelper.sendGet(
                "https://api.weixin.qq.com/cgi-bin/user/info",
                "access_token={1}&openid={2}".replace("{1}", token).replace("{2}", openid));
        try {
            info = new String(info.getBytes(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 解析响应结果
        JSONObject infoObject = JSON.parseObject(info);
        Integer errcode = (Integer) infoObject.get("errcode");
        if (errcode != null && errcode != 0) {
            // 重新获取access_token
            wechatService.getAccessToken(true);
            return this.bind(code, model);
        }
        // 得到用户信息之后返回到一个页面
        model.addAttribute("userInfo", infoObject);


        return "test";*/
    }

    @ResponseBody
    @RequestMapping(value = "/bind", method = RequestMethod.POST)
    public JsonInfo bindPage(
            @RequestParam String userLoginName,
            @RequestParam String userPassword
    ) {
        wechatService.doBindUser(userLoginName, userPassword);
        return new JsonInfo(0, "绑定成功");
    }

    @ResponseBody
    @RequestMapping(value = "/unbind", method = RequestMethod.POST)
    public JsonInfo unbindPage(
    ) {
        wechatService.doFreeUser(null);
        return new JsonInfo(0, "解绑成功");
    }

    @ResponseBody
    @RequestMapping(value = "/current-user", method = RequestMethod.GET)
    public JsonInfo currentUser() {
        JsonInfo jsonInfo = new JsonInfo(0, "绑定成功");
        jsonInfo.put("user", userService.getLoggedUser());
        return jsonInfo;
    }

    @RequestMapping("/redirect-do")
    public String redirectDO(
            @RequestParam String url,
            String sharp,
            Model model,
            HttpServletRequest request
    ) {
        model.addAttribute("projectPath", request.getContextPath());
        model.addAttribute("url", url + (sharp == null ? "" : ("#" + sharp)));
        return "redirect";
    }
}
